﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PingYou.Framework.UI
{
    public class CommonMethod
    {
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static string Md5Hash(string input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        public static string GetShortUrl(string url)
        {
            //可以自定义生成MD5加密字符传前的混合KEY
            string key = DateTime.Now.ToString();
            //要使用生成URL的字符
            string[] chars = new string[]{           
             "a","b","c","d","e","f","g","h",
             "i","j","k","l","m","n","o","p",
             "q","r","s","t","u","v","w","x",
             "y","z","0","1","2","3","4","5",
             "6","7","8","9","A","B","C","D",
             "E","F","G","H","I","J","K","L",
             "M","N","O","P","Q","R","S","T",
             "U","V","W","X","Y","Z"
              };

            //对传入网址进行MD5加密

            //string hex = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key + url, "md5");
            string hex = Md5Hash(key + url);

            string[] resUrl = new string[4];
            for (int i = 0; i < 4; i++)
            {
                //把加密字符按照8位一组16进制与0x3FFFFFFF进行位与运算
                int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
                string outChars = string.Empty;
                for (int j = 0; j < 6; j++)
                {
                    //把得到的值与0x0000003D进行位与运算，取得字符数组chars索引
                    int index = 0x0000003D & hexint;
                    //把取得的字符相加
                    outChars += chars[index];
                    //每次循环按位右移5位
                    hexint = hexint >> 5;
                }
                //把字符串存入对应索引的输出数组
                resUrl[i] = outChars;
            }
            return resUrl[new Random().Next(0, 3)];
        }

        #region 新浪短连接存储
        #region 将长链接转换为短链接
        /// <summary>
        /// 将长链接转换为短链接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ShortUrl(string url)
        {
            string shortUrl = string.Empty;
            try
            {
                Dictionary<String, String> dicList = new Dictionary<String, String>();
                dicList.Add("source", "3271760578");
                dicList.Add("url_long", url);
                string param = buildQueryStr(dicList);
                var response = DoGet("http://api.t.sina.com.cn/short_url/shorten.json", param);
                response.Wait();
                StreamReader sr = new StreamReader(response.Result.GetResponseStream(), Encoding.UTF8);
                string jsonText = sr.ReadToEnd();
                JArray result = JsonConvert.DeserializeObject(jsonText) as JArray;
                if (result.Count > 0)
                {
                    JToken token = result[0];
                    var data = token.Value<string>("url_short");
                    if (data != null)
                    {
                        shortUrl = data;
                    }
                    else
                    {
                        shortUrl = url;
                    }
                }
            }
            catch (Exception)
            {
                shortUrl = url;
            }
            return shortUrl;
        }
        #endregion

        #region public static string ExpandUrl(string url) 将短链接换为长链接
        /// <summary>
        /// 将短链接换为长链接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ExpandUrl(string url)
        {
            string longUrl = string.Empty;
            try
            {
                Dictionary<String, String> dicList = new Dictionary<String, String>();
                dicList.Add("source", "3271760578");
                dicList.Add("url_short", url);


                string param = buildQueryStr(dicList);
                var response = DoGet("http://api.t.sina.com.cn/short_url/expand.json", param);

                response.Wait();
                StreamReader sr = new StreamReader(response.Result.GetResponseStream(), Encoding.UTF8);
                string jsonText = sr.ReadToEnd();
                JArray result = JsonConvert.DeserializeObject(jsonText) as JArray;
                if (result.Count > 0)
                {
                    JToken token = result[0];
                    var data = token.Value<string>("url_long");
                    if (data != null)
                    {
                        longUrl = data;
                    }
                    else
                    {
                        longUrl = url;
                    }
                }
            }
            catch (Exception myEx)
            {
                longUrl = myEx.Message;
            }
            return longUrl;
        }
        #endregion

        private static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        /// <summary>
        /// 做get请求
        /// </summary>
        private static Task<WebResponse> DoGet(string apiUrl, string paramStr)
        {

            HttpWebRequest req = HttpWebRequest.CreateHttp(apiUrl + "?" + paramStr);
            req.Method = "GET";
            return req.GetResponseAsync();
        }

        #endregion
    }
}